//
//  MapLayersTableViewCell.m
//  dataGathering
//
//  Created by macmini on 15/3/12.
//  Copyright (c) 2015年 shuili. All rights reserved.
//

#import "MapLayersTableViewCell.h"
#import "currentWorkSetManager.h"
#import "FileDownloadManager.h"
#import "FileUtil.h"

@implementation MapLayersTableViewCell
@synthesize name;
@synthesize downloadButton;
@synthesize downloadProgress;
@synthesize visibleSwitch;


- (void)awakeFromNib {
    // Initialization code
    [downloadProgress setHidden:YES];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(void)setMainLabelString:(NSString *)mainLabelString
{
    [name setText:mainLabelString];
}

-(void)setDownloadButtonString:(NSString *)downloadButtonString
{
    [downloadButton setTitle:downloadButtonString forState:UIControlStateNormal];
    if([downloadButtonString isEqualToString:@"删除"])
    {
        //[downloadButton setImage:[UIImage imageNamed:@"_btn-primary_-regular_u36_selected.png"] forState:UIControlStateNormal];
    } else {
        //[downloadButton setImage:nil forState:UIControlStateNormal];
    }
}

-(void)setVisibleStatus:(BOOL)visible
{
    [visibleSwitch setOn:visible];
}
- (IBAction)visibleSwitchChanged:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"maplayersVisibleChange" object:[name text]];

}

- (IBAction)downloadButtonClicked:(id)sender {
    if([[downloadButton titleForState:UIControlStateNormal] isEqualToString:@"下载"])
    {
        
        _pro = [NSProgress progressWithTotalUnitCount:1000.0];
        [_pro addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
        
        [downloadProgress setHidden:NO];
        
        [FileDownloadManager downloadTPKFile:[name text] :_pro success:^{
            [downloadButton setTitle:@"删除" forState:UIControlStateNormal];
            [downloadProgress setHidden:YES];
            
             [[NSNotificationCenter defaultCenter] postNotificationName:@"offlineFileChanged" object:[name text]];
        } failure:^(NSError *error) {
            
        }];
    } else {
        [FileUtil deleteTPKFile:[name text]];
        [downloadButton setTitle:@"下载" forState:UIControlStateNormal];
        
         [[NSNotificationCenter defaultCenter] postNotificationName:@"offlineFileChanged" object:[name text]];
        
    }
    
   

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{
    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
        NSProgress *progress = (NSProgress *)object;
        NSLog(@"Download at %f", progress.fractionCompleted);
        [downloadProgress setProgress:progress.fractionCompleted];
    }

    
}
@end
